package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    public UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        // 1.查询用户
        User u = userService.findByUserName(username);
        if(u == null){
            // 没有占用
            // 2.注册
            userService.register(username, password);
            return Result.success();
        }else{
            // 占用
            return Result.success("用户名已被占用");
        }
    }

    // 登录
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        // 1.查询用户（存在：登录成功   不存在：登录失败）
        User loginUser = userService.findByUserName(username);
        if (loginUser == null) {
            return Result.error("用户名错误");
        }
        // 判断密码是否正确
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            // 生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            // 将生成的token存入redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);

            return Result.success(token);
        }
        return Result.error("密码错误");

    }
    // 获取用户详情信息
    @GetMapping("/userInfo")
    public Result<User> getLoginUser(){
        // 1.查询用户
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    // 更新用户基本信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.updateUser(user);
        return Result.success();
    }
    // 更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        // 获取到用户id
        Map<String, Object> cliams = ThreadLocalUtil.get();
        Integer id = (Integer) cliams.get("id");
        userService.updateAvatar(avatarUrl, id);
        return Result.success();
    }
    // 更新用户密码
    @PatchMapping("/updatePwd")
    public Result updatePed(@RequestBody Map<String, String> map,@RequestHeader("Authorization") String token) {
        String old_pwd = map.get("old_pwd");
        String new_pwd = map.get("new_pwd");
        String re_pwd = map.get("re_pwd");

        // 验证三个密码是否为空
        if(!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) || !StringUtils.hasLength(re_pwd)){
            return Result.error("缺少必要参数");
        }

        // 验证原密码
        Map<String, Object> cliams = ThreadLocalUtil.get();
        String username = (String) cliams.get("username");
        User user = userService.findByUserName(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(old_pwd))){
            return Result.error("原密码填写不正确");
        }

        // 验证俩个新密码是否一致
        if(!new_pwd.equals(re_pwd)){
            return Result.error("俩次输入的密码不一致");
        }
        // 更新密码
        userService.updatepwd(new_pwd);
        // 删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        return Result.success();
    }
}
